package com.ptswitch.material.pages.security;

import java.util.List;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.ActivationRequestParameter;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hxzon.project.SplitPageInfo;
import org.hxzon.tapestry5.util.TapestryEx;
import org.slf4j.Logger;

import com.ptswitch.material.model.common.Uzer;
import com.ptswitch.material.model.security.Role;
import com.ptswitch.material.pages.base.PageBase;
import com.ptswitch.material.service.RoleService;
import com.ptswitch.material.util.HlogConstants;
import com.ptswitch.material.util.security.PermissionUtil;
import com.ptswitch.material.util.security.RoleEditUtil;

public class EditRoleUser extends PageBase {
    @Inject
    private Logger logger;
    @Inject
    private RoleService roleSer;
    @InjectPage
    private ListRole listRole;
    //
    @Property
    private SplitPageInfo userPage;
    //
    @ActivationRequestParameter
    @Property
    private String username;
    @Property
    private Role role;
    @Property
    private List<Uzer> roleUsers;
    @Property
    private List<Uzer> users;

    @OnEvent(value = EventConstants.ACTIVATE)
    void init(long id) {
        checkPermitted(PermissionUtil.RoleEdit);
        //init for display or update
        role = roleSer.findById(id);
        userPage = new SplitPageInfo();
        userPage.setPageSize(10);
    }

    @SetupRender
    void display() {
        prepareUser();
    }

    private void prepareUser() {
        username = (username == null) ? "" : username;
        userPage.setRowCount(roleSer.countUserByRoleInfo(role.getId(), username, true));
        users = roleSer.listUserByRoleInfo(role.getId(), username, true, userPage.getCurrentRow(), userPage.getPageSize());
        roleUsers = RoleEditUtil.getUsers(role);
    }

    @OnEvent(value = TapestryEx.Event_BeforeGridInplaceUpdate)
    void changeUserPage() {
        prepareUser();
    }

    @OnEvent(value = EventConstants.SUCCESS, component = "update")
    Object update() {//TODO ?
        checkPermitted(PermissionUtil.RoleEdit);
        roleSer.saveUserRoles(RoleEditUtil.toNewUserRoles(roleUsers, //
                RoleEditUtil.getUsers(role), role));
        hlog(HlogConstants.updateRole, role);
        return listRole;
    }

    @OnEvent(value = EventConstants.SUCCESS, component = "search")
    Object search() {
        return this;
    }

    @OnEvent(value = EventConstants.PASSIVATE)
    Object onPassivate() {
        return role.getId();
    }

}
